package com.learn.kafka.config;

import com.google.common.collect.Maps;
import com.learn.kafka.util.PropertiesUtil;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.Map;

@Configuration
@EnableKafka
public class KafKaProducerConfig {

    public KafKaProducerConfig() {
        System.out.println("kafka生产者配置");
    }

    @Bean
    public ProducerFactory<Integer, String> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerProperties());
    }

    private Map<String, Object> producerProperties() {
        Map<String, Object> props = Maps.newHashMap();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, PropertiesUtil.getInstance().getProperty("kafka.producer.bootstrap.servers"));
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, PropertiesUtil.getInstance().getProperty("kafka.producer.key.serializer"));
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, PropertiesUtil.getInstance().getProperty("kafka.producer.value.serializer"));
        props.put(ProducerConfig.RETRIES_CONFIG, PropertiesUtil.getInstance().getProperty("kafka.producer.retries"));
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, PropertiesUtil.getInstance().getProperty("kafka.producer.batch.size"));
        props.put(ProducerConfig.LINGER_MS_CONFIG, PropertiesUtil.getInstance().getProperty("kafka.producer.linger.ms"));
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, PropertiesUtil.getInstance().getProperty("kafka.producer.buffer.memory"));
        props.put(ProducerConfig.ACKS_CONFIG, PropertiesUtil.getInstance().getProperty("kafka.producer.acks"));

        return props;
    }

    @Bean
    public KafkaTemplate<Integer,String> kafkaTemplate(){
        KafkaTemplate kafkaTemplate = new KafkaTemplate<Integer, String>(producerFactory(),true);
        kafkaTemplate.setDefaultTopic(PropertiesUtil.getInstance().getProperty("kafka.producer.defaultTopic"));
        return kafkaTemplate;
    }

}
